<!Doctype html>
<html>
<head>
    <meta charset="utf-8" />
    <title>html5 image to base64</title>
</head>
<body>
<script type="text/javascript">
    window.onload = function(){
// 抓取上传图片，转换代码结果，显示图片的dom
        var img_upload=document.getElementById("img_upload");

// 添加功能出发监听事件
        img_upload.addEventListener('change',readFile,false);}
    function readFile(){
        var file=this.files[0];
        if(!/image\/\w+/.test(file.type)){
            alert("请确保文件为图像类型");
            return false;
        }
        var reader=new FileReader();
        reader.readAsDataURL(file);
        reader.onload=function(){
            var base64 = "";
            testbase64 = this.result.replace("data:image/jpeg;base64,","");
            console.log(testbase64);
            img_area.innerHTML = '<div>图片img标签展示：</div><img src="'+this.result+'" alt=""/>';
        }
    }
</script>
<input type="file" id="img_upload"/>
<p id="img_area"></p>
</body>
</html>